'use strict';

/**
 * @name CreateUserCtrl
 * @author ZYF
 */

angular.module('metalabOperationApp').controller('UserModelCtrl', ['$scope', '$stateParams', '$rootScope', '$state', 'params', 'MetaResources', 'MetaRemind', '$uibModalInstance', function($scope, $stateParams, $rootScope, $state, params, MetaResources, MetaRemind, $uibModalInstance) {
    $scope.user = {};
    $scope.model = {};
    $scope.backup = {};
    //true的话为创建
    if (params.flag) {
        $scope.model.title = "创建用户";
        $scope.model.positive = "创 建";
        $scope.model.negative = "清 空";
        $scope.user.role = params.data.type;
    } else {
        $scope.model.title = "编辑用户";
        $scope.model.positive = "保 存";
        $scope.model.negative = "重 置";
        MetaResources.user.get({
                'id': params.data.id
            },
            function(data) {
                $scope.user = data;
                $scope.backup = angular.copy($scope.user);
            },
            function(error) {
                MetaRemind.serverError(error);
            });
    }

    $scope.positive = function() {
        if (params.flag) {
            $scope.create();
        } else {
            $scope.save();
        }
    };

    $scope.create = function() {
        MetaResources.user.create({}, $scope.user,
            function() {
                MetaRemind.success("恭喜", "创建成功");
                $state.reload();
            },
            function(error) {
                MetaRemind.serverError(error);
            });
        $uibModalInstance.dismiss('cancel');
    };

    $scope.save = function() {
        MetaResources.user.save({
                'id': params.data.id
            }, $scope.user,
            function() {
                MetaRemind.success("恭喜", "保存成功");
                $state.reload();
            },
            function(error) {
                MetaRemind.serverError(error);
            });
        $uibModalInstance.dismiss('cancel');
    };

    $scope.negative = function() {
        $scope.user = angular.copy($scope.backup);
    };

    $scope.cancel = function() {
        $uibModalInstance.dismiss('cancel');
    };

}]);
